package com.jinyou.chengfengshop.activity;

import android.Manifest;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jinyou.chengfengshop.Constant.AppUrl;
import com.jinyou.chengfengshop.OkHttpUtils.CallBackUtil;
import com.jinyou.chengfengshop.OkHttpUtils.OkhttpUtil;
import com.jinyou.chengfengshop.R;
import com.jinyou.chengfengshop.bean.ShopTypeBean;
import com.jinyou.chengfengshop.bean.UploadImageBean;
import com.jinyou.chengfengshop.utils.BaseRequestParams;
import com.jinyou.chengfengshop.utils.CountDownTimerUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 商户入住
 * Created by zhuzhiqiang on 2018/9/27.
 */

public class ShopRegistActivity extends AppCompatActivity {
    private EditText shopName_edt;//商家名称
    private EditText userName_edt;//负责人姓名
    private TextView sex_tv;//性别
    private EditText phone_edt;//手机
    private EditText ident_edt;//验证码
    private Button btn_cutdown;//获取验证码
    private EditText userAdd_edt;//商家地址
    private TextView sale_tv;//商家经营品类
    private TextView choose_sale;//选择经营品类
    private LinearLayout photo_ll;//拍照  获取照片
    private ImageView photo_img;
    private TextView sub_tv;//注册提交

    private CountDownTimerUtils mCountDownTimerUtils;

    private String catalogId = "";//经营品类ID
    private String company = "";// 负责人
    private String name = "";// 姓名
    private String sex = "";//性别
    private String position = "";//商家地址
    private String username = "";//手机号
    private String telCode = "";//验证码
    private String sysCustomer = "o2o-chengfeng";
    private File file;

    private List<ShopTypeBean> stb;


    public static final int PHOTO_REQUEST_CAREMA = 1;// 拍照
    public static final int CROP_PHOTO = 2;
    private final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    private Uri imageUri;
    public static File tempFile;
    private String orderJson;
    String[] permissions = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CALL_PHONE
    };
    // 声明一个集合，在后面的代码中用来存储用户拒绝授权的权
    List<String> mPermissionList = new ArrayList<>();
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 1;
    private static final int MY_PERMISSIONS_REQUEST_CALL_CAMERA = 2;

    private String filename;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopregist);

        initView();
        shopType();

        Resources res = ShopRegistActivity.this.getResources();
        Bitmap bmp= BitmapFactory.decodeResource(res, R.mipmap.ic_launcher);

         file = compressImage(bmp);
    }



    private void initView() {
        shopName_edt = (EditText) findViewById(R.id.shopName_edt);
        userName_edt = (EditText) findViewById(R.id.userName_edt);
        sex_tv = (TextView) findViewById(R.id.sex_tv);
        phone_edt = (EditText) findViewById(R.id.phone_edt);
        ident_edt = (EditText) findViewById(R.id.ident_edt);
        userAdd_edt = (EditText) findViewById(R.id.userAdd_edt);
        btn_cutdown = (Button) findViewById(R.id.btn_cutdown);
        sale_tv = (TextView) findViewById(R.id.sale_tv);
        choose_sale = (TextView) findViewById(R.id.choose_sale);
        photo_ll = (LinearLayout) findViewById(R.id.photo_ll);
        photo_img = (ImageView) findViewById(R.id.photo_img);
        sub_tv = (TextView) findViewById(R.id.sub_tv);
        sub_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shopRegist();
            }
        });
        btn_cutdown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    String m = phone_edt.getText().toString();
                    if (m.length() == 11) {
                        sendCode(phone_edt.getText().toString());
                    } else {
                        Toast.makeText(getApplicationContext(), "手机号格式不正确", Toast.LENGTH_SHORT).show();
                    }


            }
        });
        mCountDownTimerUtils = new CountDownTimerUtils(btn_cutdown, 30000, 1000);
        choose_sale.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showShopType();
            }
        });

        photo_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openCamera();
            }
        });


        sex_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSex();
            }
        });


    }



    private void showSex(){

        final String[] strArray ={"男","女"};
                AlertDialog.Builder builder2 = new AlertDialog.Builder(this);//实例化builder
                builder2.setIcon(R.mipmap.ic_launcher);//设置图标
                builder2.setTitle("选择性别");//设置标题
                //设置列表
                builder2.setItems(strArray, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        sex_tv.setText(strArray[which]);
                        sex = strArray[which];
                    }
                });

        builder2.create().show();//创建并显示对话框
    }


    public void openCamera() {

        //获取系統版本
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        // 激活相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 判断存储卡是否可以用，可用进行存储
        if (hasSdcard()) {
            SimpleDateFormat timeStampFormat = new SimpleDateFormat(
                    "yyyyMMddHHmmss");
            filename = timeStampFormat.format(new Date());
            tempFile = new File(Environment.getExternalStorageDirectory(),
                    filename + ".png");
            if (currentapiVersion < 24) {
                // 从文件中创建uri
                imageUri = Uri.fromFile(tempFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            } else {
                //兼容android7.0 使用共享文件的形式
                ContentValues contentValues = new ContentValues(1);
                contentValues.put(MediaStore.Images.Media.DATA, tempFile.getAbsolutePath());
                //检查是否有存储权限，以免崩溃
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请WRITE_EXTERNAL_STORAGE权限
                    reqPermission();
                    Toast.makeText(this,"请开启存储权限",Toast.LENGTH_SHORT).show();
                    return;
                }
                imageUri = Uri.fromFile(tempFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//                imageUri = getApplicationContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
//                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            }
        }
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA
        startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
    }

    /*
    * 判断sdcard是否被挂载
    */
    public static boolean hasSdcard() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }


    //获取拍照储存权限
    private void reqPermission(){
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(ShopRegistActivity.this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);
            }
        }
        if (mPermissionList.isEmpty()) {//未授予的权限为空，表示都授予了


            //openCamera(routeAddrId,routeId);

            //Toast.makeText(AddOrderPhotoActivity.this,"已经授权",Toast.LENGTH_LONG).show();
        } else {//请求权限方法
            String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
            ActivityCompat.requestPermissions(ShopRegistActivity.this, permissions, MY_PERMISSIONS_REQUEST_CALL_CAMERA);
        }
    }



    /**
     * 压缩图片（质量压缩）
     * @param bitmap
     */
    public static File compressImage(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 500) {  //循环判断如果压缩后图片是否大于500kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            options -= 10;//每次都减少10
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            long length = baos.toByteArray().length;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date(System.currentTimeMillis());
        String filename = format.format(date);
        File file = new File(Environment.getExternalStorageDirectory(),filename+".png");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            try {
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {
                //BAFLogger.e(TAG,e.getMessage());
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            //BAFLogger.e(TAG,e.getMessage());
            e.printStackTrace();
        }
        recycleBitmap(bitmap);
        return file;
    }

    public static void recycleBitmap(Bitmap... bitmaps) {
        if (bitmaps==null) {
            return;
        }
        for (Bitmap bm : bitmaps) {
            if (null != bm && !bm.isRecycled()) {
                bm.recycle();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case PHOTO_REQUEST_CAREMA:
                if (resultCode == RESULT_OK) {
                    //addOrderD(Environment.getExternalStorageDirectory()+"/"+filename+".png");

                }
                break;
            case CROP_PHOTO:
                if (resultCode == RESULT_OK) {
                    try {
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver()
                                .openInputStream(imageUri));


                        //photo_img.setImageBitmap(bitmap);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }


    //发送验证码
    private void sendCode(final String mPhone) {
        HashMap<String, String> paramsMap = new HashMap<>();

        paramsMap.put("username", mPhone);
        paramsMap.put("sysCustomer", "o2o-chengfeng");

        OkhttpUtil.okHttpPost(AppUrl.SHOP_REGIST_CODE, paramsMap, new CallBackUtil.CallBackString() {
            @Override
            public void onFailure(Call call, Exception e) {
                Toast.makeText(ShopRegistActivity.this, "失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response) {//请求成功时调用，执行在UI线程
                try {
                    JSONObject obj = new JSONObject(response);
                    int code = obj.getInt("status");
                    if (code == 1) {
                        mCountDownTimerUtils.start();
                    } else {
                        Toast.makeText(ShopRegistActivity.this, obj.getString("error"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }



    private void showShopType(){


        if(stb.size()<1){
            return;
        }

        final String[] strArray = new String[stb.size()];//创建itemAlert
        for(int i = 0;i<stb.size();i++){
            strArray[i] = stb.get(i).getName();
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);//实例化builder
        builder.setIcon(R.mipmap.ic_launcher);//设置图标
        builder.setTitle("经营品类");//设置标题
        //设置列表
        builder.setItems(strArray, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                sale_tv.setText(strArray[which]);
                catalogId = stb.get(which).getId();
                //Toast.makeText(getApplicationContext(),strArray[which],Toast.LENGTH_SHORT).show();
            }
        });


        builder.create().show();//创建并显示对话框

    }


    //获取经营品类
    private void shopType() {
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("sysCustomer", "o2o-chengfeng");

        OkhttpUtil.okHttpPost(AppUrl.SHOP_TYPE, paramsMap, new CallBackUtil.CallBackString() {
            @Override
            public void onFailure(Call call, Exception e) {
                Toast.makeText(ShopRegistActivity.this, "失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response) {//请求成功时调用，执行在UI线程
                try {
                    JSONObject obj = new JSONObject(response);
                    int code = obj.getInt("status");
                    if (code == 1) {
                        String ob = obj.getString("data");
                        if (ob != null && !ob.equals("")) {
                            Type typeOfT = new TypeToken<List<ShopTypeBean>>() {
                            }.getType();
                            stb = new Gson().fromJson(ob, typeOfT);
                        }
                    } else {
                        Toast.makeText(ShopRegistActivity.this, obj.getString("error"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }




    //商户申请
    private void shopRegist(){
        company = shopName_edt.getText().toString();
        if(company.equals("")){
            Toast.makeText(getApplicationContext(),"请输入商家昵称",Toast.LENGTH_SHORT).show();
            return;
        }

        name = userName_edt.getText().toString();
        if(name.equals("")){
            Toast.makeText(getApplicationContext(),"请输入商家昵称",Toast.LENGTH_SHORT).show();
            return;
        }

        if(sex.equals("")){
            Toast.makeText(getApplicationContext(),"请选择性别",Toast.LENGTH_SHORT).show();
            return;
        }

        position = userAdd_edt.getText().toString();
        if(position.equals("")){
            Toast.makeText(getApplicationContext(),"请输入商家地址",Toast.LENGTH_SHORT).show();
            return;
        }

        username = phone_edt.getText().toString();
        if(username.equals("")){
            Toast.makeText(getApplicationContext(),"请输入手机号",Toast.LENGTH_SHORT).show();
            return;
        }

        telCode = ident_edt.getText().toString();
        if(telCode.equals("")){
            Toast.makeText(getApplicationContext(),"请输入验证码",Toast.LENGTH_SHORT).show();
            return;
        }




        if(catalogId.equals("")){
            Toast.makeText(getApplicationContext(),"请选择经营品类",Toast.LENGTH_SHORT).show();
            return;
        }



//        HashMap<String, String> paramsMap = new HashMap<>();
//        paramsMap.put("sysCustomer", "o2o-chengfeng");
//        paramsMap.put("catalogId",catalogId);
//        paramsMap.put("company", company);
//        paramsMap.put("name",name);
//        paramsMap.put("position",position);
//        paramsMap.put("sex",sex);
//        paramsMap.put("telCode",telCode);
//        paramsMap.put("username",username);
//
//        OkhttpUtil.okHttpPost(AppUrl.SHOP_REGIST, paramsMap, new CallBackUtil.CallBackString() {
//            @Override
//            public void onFailure(Call call, Exception e) {
//                Toast.makeText(ShopRegistActivity.this, "失败", Toast.LENGTH_SHORT).show();
//            }
//
//            @Override
//            public void onResponse(String response) {//请求成功时调用，执行在UI线程
//                try {
//                    JSONObject obj = new JSONObject(response);
//                    int code = obj.getInt("status");
//                    if (code == 1) {
//                        String ob = obj.getString("data");
//                        if (ob != null && !ob.equals("")) {
////                            Type typeOfT = new TypeToken<List<ShopTypeBean>>() {
////                            }.getType();
////                            stb = new Gson().fromJson(ob, typeOfT);
//                        }
//                    } else {
//                        Toast.makeText(ShopRegistActivity.this, obj.getString("error"), Toast.LENGTH_SHORT).show();
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//
//            }
//        });

        registShop(new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                UploadImageBean bean = new Gson().fromJson(responseInfo.result, UploadImageBean.class);
                if (1 == bean.getStatus()) {
                    Toast.makeText(getApplicationContext(),"注册成功", Toast.LENGTH_SHORT).show();
                    finish();

                } else {
                    Toast.makeText(getApplicationContext(),"注册失败", Toast.LENGTH_SHORT).show();
                }
                //Toast.makeText(getApplicationContext(), responseInfo.toString(), Toast.LENGTH_SHORT).show();
                finish();
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();

            }
        });

    }

    //上传图片
    private void registShop(RequestCallBack<String> callback) {

        try {

            HttpUtils httpUtils = new HttpUtils(10000);
            RequestParams params = new BaseRequestParams().getParams();
            if (file != null) {

                params.addBodyParameter("sysCustomer", "o2o-chengfeng");
                params.addBodyParameter("catalogId",catalogId);
                params.addBodyParameter("company", company);
                params.addBodyParameter("name",name);
                params.addBodyParameter("position",position);
                params.addBodyParameter("sex",sex);
                params.addBodyParameter("telCode",telCode);
                params.addBodyParameter("username",username);
                params.addBodyParameter("file03", file,"image/png");
            }
            httpUtils.send(HttpMethod.POST, AppUrl.SHOP_REGIST, params, callback);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

}